import { ref } from 'vue';

import pagesJson from '@/pages.json';
import { defineStore } from 'pinia';

const uniIdCo = uniCloud.importObject('uni-id-co');
const db = uniCloud.database();
const usersTable = db.collection('uni-id-users');

// 定义类型
interface UserInfo {
	mobile?: string;
	nickname?: string;
	username?: string;
	email?: string;
	role?: string[];
	permission?: string[];
	_id?: string;
	[key: string]: any;
}

interface LoginOptions {
	cover?: boolean;
}

export const useAuthStore = defineStore('auth', () => {
	// 初始化用户信息
	const hostUserInfo = uni.getStorageSync('uni-id-pages-userInfo') || {};
	// 状态
	const userInfo = ref<UserInfo>(hostUserInfo);
	const hasLogin = ref<boolean>(Object.keys(hostUserInfo).length !== 0);

	const { message } = useFeedback(['message']);

	// 方法
	async function updateUserInfo(data?: UserInfo) {
		if (data) {
			try {
				const result = await usersTable.where('_id==$env.uid').update(data);
				if (result.result.updated) {
					message.success('更新成功');

					setUserInfo(data);
				} else {
					message.success('没有改变');
				}
			} catch (error) {
				console.error('更新用户信息失败:', error);
			}
		} else {
			// 不等待联网查询，立即更新用户_id确保store.userInfo中的_id是最新的
			const _id = uniCloud.getCurrentUserInfo().uid;
			setUserInfo({ _id }, { cover: true });

			// 查库获取用户信息，更新store.userInfo
			try {
				const res = await usersTable.where("'_id' == $cloudEnv_uid").field('mobile,nickname,username,email,avatar_file').get();

				setUserInfo({
					...res.result.data[0],
				});
			} catch (e) {
				setUserInfo({}, { cover: true });
				console.error(e);
			}
		}
	}

	function setUserInfo(data: UserInfo, { cover }: LoginOptions = { cover: false }) {
		const newUserInfo = cover ? data : Object.assign(userInfo.value, data);
		userInfo.value = Object.assign({}, newUserInfo);
		hasLogin.value = Object.keys(userInfo.value).length !== 0;
		uni.setStorageSync('uni-id-pages-userInfo', userInfo.value);
		return data;
	}

	async function logout() {
		// 1. 已经过期就不需要调用服务端的注销接口 2.即使调用注销接口失败，不能阻塞客户端
		// @ts-ignore
		if (uniCloud.getCurrentUserInfo().tokenExpired > Date.now()) {
			try {
				await uniIdCo.logout();
			} catch (e) {
				console.error(e);
			}
		}
		uni.removeStorageSync('uni_id_token');
		uni.removeStorageSync('opendb-admin-menus');
		uni.setStorageSync('uni_id_token_expired', 0);
		setUserInfo({}, { cover: true });
		uni.$emit('uni-id-pages-logout');
		uni.redirectTo({
			url: `/${pagesJson.uniIdRouter && pagesJson.uniIdRouter.loginPage ? pagesJson.uniIdRouter.loginPage : 'pages/login/index'}`,
		});
	}

	function loginSuccess() {
		// 异步调用（更新用户信息）防止获取头像等操作阻塞页面返回
		updateUserInfo();

		uni.$emit('uni-id-pages-login-success');
	}

	return {
		// 状态
		userInfo,
		hasLogin,
		// 方法
		updateUserInfo,
		setUserInfo,
		logout,
		loginSuccess,
	};
});

export const useAuthStoreHook = () => {
	return useAuthStore(store);
};
